﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Management;
using System.Management.Instrumentation;
using YSTools;
using System.Configuration;

namespace Strongbox
{
    public class Utils
    {
        public static String MachineCode = ""; // 机器码
        public static String skin = "green";
        public static String softName = "Strongbox";
        public static string MyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        public static String baseDir = MyDocuments + "\\Strongbox\\";
        public static string xmlPath = baseDir + "config.xml";
        // 密钥 32 位长度
        public static String abkey = "Ind*&h4_fJPc-f2kjd-fd4{}ddce489d";
        public static String cdkey = "Jiofd894j89(4h__9dj4^fddq734ZMd2";
        public static String filekey = "68UY&*^%gfhHNJK987k%&k52563Kje4{";
        public static String account_w = "";
        public static String password_w = "";
        public static String lockPwd = "1";
        public static String autoStart = "1"; // 1不开机启动，2开机启动
        public static List<String> appImageList = new List<String>();

        public static long lastOparateTime = DateTime.Now.Ticks;

        public static void SetLastOparateTime()
        {
            lastOparateTime = DateTime.Now.Ticks;
        }

        /// <summary>
        /// 获取图片对象
        /// </summary>
        /// <param name="type">1默认，2焦点，3点击</param>
        /// <param name="name">图片名字</param>
        /// <param name="name">图片后缀.png、.ico</param>
        /// <returns></returns>
        public Image GetImage(String name, int type = 0, String zui = ".png")
        {
            Image img = null;
            try
            {
                String typeName = type == 0 ? "" : type == 1 ? "_active" : "_pres";
                img = Image.FromFile(String.Format("resource/images/{0}{1}{2}", name, typeName, zui));
            }
            catch (Exception)
            {
                img = null;
            }
            return img;
        }

        /// <summary>
        /// 获取图片对象
        /// </summary>
        /// <param name="type">1默认，2焦点，3点击</param>
        /// <param name="name">图片名字</param>
        /// <returns></returns>
        public Image GetImageBySkin(String name, int type = 0, String zui = ".png")
        {
            Image img = null;
            try
            {
                String typeName = type == 0 ? "" : type == 1 ? "_active" : "_pres";
                img = Image.FromFile(String.Format("resource/skin/{0}/{1}{2}{3}", skin, name, typeName, zui));
            }
            catch (Exception)
            {
                img = null;
            }
            return img;
        }

        /// <summary>
        /// 读取配置
        /// </summary>
        public void loadConfig()
        {
            String data = "";
            byte[] bytes = null;
            List<Hashtable> list = YSTools.YSXml.readXml(xmlPath, "configs", true, cdkey);
            foreach (Hashtable table in list)
            {
                if (table["NodeName"].ToString().Equals("skin"))
                {
                    skin = table["InnerText"].ToString();
                }
                else if (table["NodeName"].ToString().Equals("autoStart"))
                {
                    autoStart = table["InnerText"].ToString();
                }
                else if (table["NodeName"].ToString().Equals("lockPwd"))
                {
                    lockPwd = table["InnerText"].ToString();
                }
                else if (table["NodeName"].ToString().Equals("account"))
                {
                    account_w = table["InnerText"].ToString();
                } 
                else if (table["NodeName"].ToString().Equals("password"))
                {
                    password_w = table["InnerText"].ToString();
                }
                else if (table["NodeName"].ToString().Equals("tree"))
                {
                    data = table["InnerText"].ToString();

                    data = YSEncrypt.DecryptB(covertBase64(data), abkey);
                    bytes = Convert.FromBase64String(data);
                    Form1.treeList = YSConvert.ByteToObject(bytes) as List<TreeObj>;
                    Form1.treeCount = Form1.treeList == null ? 0 : Form1.treeList.Count;
                }
                else if (table["NodeName"].ToString().Equals("imageList"))
                {
                    data = table["InnerText"].ToString();

                    data = YSEncrypt.DecryptB(covertBase64(data), abkey);
                    bytes = Convert.FromBase64String(data);
                    appImageList = YSConvert.ByteToObject(bytes) as List<String>;
                }
            }           

        }

        /// <summary>
        /// 保存配置
        /// </summary>
        public void saveData(bool upload = true)
        {
            List<Hashtable> list = new List<Hashtable>();
            // 皮肤
            Hashtable table = new Hashtable();
            table.Add("NodeName", "skin");
            table.Add("InnerText", skin);
            list.Add(table);
            // 锁屏密码
            table = new Hashtable();
            table.Add("NodeName", "lockPwd");
            table.Add("InnerText", lockPwd);
            list.Add(table);
            // 是否开机启动
            table = new Hashtable();
            table.Add("NodeName", "autoStart");
            table.Add("InnerText", autoStart);
            list.Add(table);

            // 账号
            table = new Hashtable();
            table.Add("NodeName", "account");
            table.Add("InnerText", account_w);
            list.Add(table);

            // 密码
            table = new Hashtable();
            table.Add("NodeName", "password");
            table.Add("InnerText", password_w);
            list.Add(table);

            // 数据
            table = new Hashtable();
            byte[] objByte = YSTools.YSConvert.ObjectToByte(Form1.treeList);
            String data = Convert.ToBase64String(objByte);
            data = YSTools.YSEncrypt.EncryptA(data, abkey);
            table.Add("NodeName", "tree");
            table.Add("InnerText", filterBase64(data));
            list.Add(table);

            Hashtable table22 = new Hashtable();
            List<String> appImageList2 = new List<String>();
            for (int i = 0; i < appImageList.Count; i++)
            {
                if (!table22.ContainsKey(appImageList[i]))
                {
                    table22.Add(appImageList[i], "22");
                    appImageList2.Add(appImageList[i]);
                }
            }
            appImageList = appImageList2;

            // 图标数据
            table = new Hashtable();
            objByte = YSTools.YSConvert.ObjectToByte(appImageList);
            data = Convert.ToBase64String(objByte);
            data = YSTools.YSEncrypt.EncryptA(data, abkey);
            table.Add("NodeName", "imageList");
            table.Add("InnerText", filterBase64(data));
            list.Add(table);

            YSTools.YSXml.WriteXml(xmlPath, list, "configs", true, cdkey);          
        }

        public String filterBase64(String base64)
        {
            base64 = base64.Replace("+", ",");
            base64 = base64.Replace("=", "_");
            base64 = base64.Replace("/", "-");
            return base64;
        }

        public String covertBase64(String base64)
        {
            base64 = base64.Replace(",", "+");
            base64 = base64.Replace("_", "=");
            base64 = base64.Replace("-", "/");
            return base64;
        }

        public void ExitApplication()
        {
            //saveData();
            System.Environment.Exit(0);
        }

        public void LockStrongBox(bool hide)
        {
            if (Utils.lockPwd != null && Utils.lockPwd.Equals("1"))
            {
                Program.form1.firstLockStrongbox();
            }
            else
            {
                LockScreen.initPwd = false;
                if (Form1.islock)
                {
                    // 显示解锁窗口
                    Program.form1.ShowHideLockScreen(true);
                }
                else
                {
                    // 锁定软件
                    Program.form1.LockOrNoForm(true);
                    if (!hide)
                    {
                        // 显示解锁窗口
                        Program.form1.ShowHideLockScreen(true);
                    }
                }
            }
        }

        public static string GetInfo()
        {
            string cpuInfo = "";//cpu序列号  
            String NetId = "";//网卡硬件地址 
            try
            {
                ManagementClass cimobject = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = cimobject.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                //获取硬盘ID
                /**
                String HDid = "";
                ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc1 = cimobject1.GetInstances();
                foreach (ManagementObject mo in moc1)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                }
                **/
                // 获取网卡硬件地址
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc2 = mc.GetInstances();
                foreach (ManagementObject mo in moc2)
                {
                    if ((bool)mo["IPEnabled"] == true)
                        NetId += mo["MacAddress"].ToString();
                    mo.Dispose();
                }
            }
            catch
            {
            }
            return cpuInfo + NetId;
        }


    }
}
